package cn.est.service.impl;
import cn.est.dto.UsersDto;
import cn.est.mapper.UsersMapper;
import cn.est.pojo.Users;
import cn.est.service.UsersService;
import javax.annotation.Resource;

import cn.est.utils.UUIDUtils;
import cn.est.utils.UrlUtils;
import cn.est.utils.redis.RedisKeyUtils;
import cn.est.utils.redis.RedisUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import cn.est.dto.Page;
import cn.est.constants.Constants;
import cn.est.utils.EmptyUtils;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UsersServiceImpl implements UsersService {
    Logger log = LoggerFactory.getLogger(UsersServiceImpl.class);
    @Resource
    private UsersMapper usersMapper;

    @Autowired
    private RedisUtils redisUtils;

    public Users getUsersById(Long id){
        return usersMapper.getUsersById(id);
    }

    public List<Users>	getUsersListByMap(Map<String,Object> param){
        return usersMapper.getUsersListByMap(param);
    }

    public Integer getUsersCountByMap(Map<String,Object> param){
        return usersMapper.getUsersCountByMap(param);
    }

    public Integer qdtxAddUsers(Users users){
            users.setCreatedTime(new Date());
            return usersMapper.insertUsers(users);
    }

    public Integer qdtxModifyUsers(Users users){
        users.setUpdatedTime(new Date());
        return usersMapper.updateUsers(users);
    }

    public Integer qdtxDeleteUsersById(Long id){
        return usersMapper.deleteUsersById(id);
    }

    public Integer qdtxBatchDeleteUsers(String ids){
        Map<String,List<String>> param=new HashMap<String,List<String>>();
        String[] paramArrays=ids.split(",");
        List<String> idList=new ArrayList<String>();
            for (String temp:paramArrays){
                idList.add(temp);
            }
        param.put("ids",idList);
        return usersMapper.batchDeleteUsers(param);
    }

    /**
     * 根据手机号查询用户信息
     *
     * @param phone
     * @return
     */
    @Override
    public UsersDto getByPhone(String phone) {
        UsersDto users = usersMapper.selectByPhone(phone);
        return users;
    }
    public Page<Users> queryUsersPageByMap(Map<String,Object> param,Integer pageNo,Integer pageSize){
        Integer total = usersMapper.getUsersCountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Page.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Page.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<Users> usersList = usersMapper.getUsersListByMap(param);
        page.setList(usersList);
        return page;
     }



    /**
     * 设置用户登录
     *
     * @param usersDto
     */
    public void setToken(UsersDto usersDto) {
        String token = UUIDUtils.getUUID32();
        usersDto.setToken(token);
        String key = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_TOKEN, token);
        redisUtils.putValue(key, JSON.toJSON(usersDto).toString(), Constants.Duration.HALF_AN_HOUR);
    }
    /**
     * 微信扫描登录、注册
     * @param accessToken
     * @param openId
     * @return
     * @throws Exception
     */
    @Override
    public UsersDto loginByWechat(String accessToken, String openId) {
        UsersDto usersDto = usersMapper.selectByOpenId(openId);
        // 1.如果用户不存在，说明是第一次登录，创建一个用户
        if(usersDto == null){
            Users users = new Users(null, openId, openId);
            Map<String,Object> map = wechatUserInfo(accessToken, openId);
            if (map != null){
                if(map.get("nickname") != null){
                    users.setUserName(map.get("nickname").toString());
                }
                if(map.get("headimgurl") != null){
                    users.setFaceUrl(map.get("headimgurl").toString());
                }
                if(map.get("sex") != null){
                    users.setSex(Integer.parseInt(map.get("sex").toString()));
                }
            }
            usersMapper.insertUsers(users);
            usersDto = new UsersDto(users);
        }
        // 2.登录，将用户信息缓存到redis中
        setToken(usersDto);
        return usersDto;
    }
    /**
     * 设置用户登录
     *
     * @param users
     */
    public void setToken(Users users) {
        String token = UUIDUtils.getUUID32();
        UsersDto usersDto = new UsersDto();
        setToken(usersDto);
    }
    /**
     * 获取微信用户信息
     * @param accessToken
     * @param openid
     * @return
     */
    public Map<String, Object> wechatUserInfo(String accessToken, String openid){
        Map<String, Object> userInfo = null;
        try {
            //加载用户信息
            String userInfoJson = UrlUtils.loadURL("https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid);
            userInfo = JSON.parseObject(userInfoJson, Map.class);
        } catch (Exception e) {
            log.error("授权失败", e.getMessage());
        }
        return  userInfo;
    }

    /**
     * 用户登录--验证码
     *
     * @param phone
     * @return
     */
    @Override
    public UsersDto loginByPhone(String phone) {
        UsersDto userDto = usersMapper.selectByPhone(phone);
        // 1.如果用户不存在，说明是第一次登录，创建一个用户
        if (userDto == null) {
            Users users = new Users(phone, null, phone);
            usersMapper.insertUsers(users);
            setToken(users);
        } else {
            // 2.登录，将用户信息缓存到redis中
            setToken(userDto);
        }
        // 3.将验证码置为无效
        String key = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_SMS, Constants.Sms.TYPE_REGIST_OR_LOGIN.toString(), phone);
        redisUtils.delete(key);
        return userDto;
    }


}
